#include "TreeNode.h"
#include "SFont.h"
#include "ResourceMgr.h"
#include "Gfx.h"
#include "SDL.h"
#include <string>
using namespace std;

void
TreeNode::
createTextSurfaces_ () {
	SFont_Font *font = ResourceMgr::instance()->getFont("Font64.png");
	int w, h;
	const char *textChar = text_.c_str();
	SDL_Surface *screen = Gfx::instance()->getScreen();

	w = SFont_TextWidth(font, textChar);
	h = SFont_TextHeight(font);

	SDL_Surface *tmp = SDL_CreateRGBSurface (SDL_ANYFORMAT,
			w, h, 32, 0, 0, 0, 0);
	SFont_WriteCenter (tmp, font, 0, textChar);

	textSurface_ = SDL_DisplayFormat(tmp);
	SDL_SetColorKey(textSurface_, SDL_SRCCOLORKEY, 0);
	SDL_FreeSurface(tmp);

	tmp = SDL_CreateRGBSurface (SDL_ANYFORMAT,
			textSurface_->w, textSurface_->h, 32, 0, 0, 0, 0);

	SDL_Rect src, dst;
	src.x = (screen->w - textSurface_ ->w) / 2;
	src.y = 496 - textSurface_->h / 2;
	src.w = tmp->w;
	src.h = tmp->h;

	dst.x = 0;
	dst.y = 0;
	dst.w = src.w;
	dst.h = src.h;

	SDL_BlitSurface(screen, &src, tmp, &dst);
	textMask_ = SDL_DisplayFormat(tmp);
	SDL_FreeSurface(tmp);
	
	// Don't get confused, the "source" and "destination"
	// rectangles are inverted because we're gonna do
	// the reverse blit: from surface to screen, later.
	srcRect_.x = dst.x;
	srcRect_.y = dst.y;
	srcRect_.w = dst.w;
	srcRect_.h = dst.h;

	dstRect_.x = src.x;
	dstRect_.y = src.y;
	dstRect_.w = src.w;
	dstRect_.h = src.h;
}

void
TreeNode::
blitMask () {
	SDL_Surface *screen = Gfx::instance()->getScreen();
	// Blit Mask
	SDL_BlitSurface (textMask_, &srcRect_, screen, &dstRect_);
	// Update could be done at one in the MenuScreen
	// but let's do it this way for the moment
	SDL_UpdateRects (screen, 1, &dstRect_);
}


void
TreeNode::
blitText () {
	SDL_Surface *screen = Gfx::instance()->getScreen();
	// Blit Mask
	SDL_BlitSurface (textSurface_, &srcRect_, screen, &dstRect_);
	// Update could be done at one in the MenuScreen
	// but let's do it this way for the moment
	SDL_UpdateRects (screen, 1, &dstRect_);
}


